package cn.jm.study.ini;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class IniReader {

	private final static String FILE_NAME = "config.ini";

	private String getFilePath() {
		// System.getProperty("user.dir") 获取当前运行程序的文件夹
		// File.separator 目录分割符,windows 为 "\",linux系统为 "/"
		return System.getProperty("user.dir") + File.separator + FILE_NAME; // 获取当前程序下的config.ini 完整路径
	}

	public Map<String, String> read() {

		Map<String, String> result = new HashMap<String, String>(); // 返回值的初始化

		File iniFile = new File(getFilePath());

		// 文件不存在，返回null
		if (!iniFile.exists()) {
			return result;
		}
		try {
			LineNumberReader iniInput = new LineNumberReader(new FileReader(iniFile));
			String line;
			while ((line = iniInput.readLine()) != null) {
				String[] lineData = getLineData(line);
				if (lineData != null) {
					result.put(lineData[0], lineData[1]);
				}
			}
			iniInput.close();
		} catch (FileNotFoundException e) {
			return result;
		} catch (IOException e) {
			return result;
		}

		return result;
	}

	public String[] getLineData(String line) {
		int postion = 0;
		String[] result = new String[2];
		if (line == null || line.length() < 1) {
			return null;
		}
		postion = line.indexOf("=");

		if (postion < 1) {
			return null;
		}
		result[0] = line.substring(0, postion);
		result[1] = line.substring(postion + 1, line.length());

		return result;
	}
	
		/**
		 * 
		 *  printf("格式化字串",变量，，，，，)
		 * 
		 * %d  整数
		 * %f 小数
		 * %s 字符串
		 * %c 字符
		 * 
		 * 
		 * @param data
		 */

	public void write(Map<String, String> data) {
		File iniFile = new File(getFilePath());
		if(data == null) {
			return;
		}
		if(data.size()<1) {
			return;
		}
		try {
			PrintWriter out = new PrintWriter(new FileWriter(iniFile));
			for(Entry<String, String> item:data.entrySet()) {
				out.printf("%s=%s\n", item.getKey(),item.getValue());
			}
			out.close();
		} catch (IOException e) {
			return;
		}
		

	}

}
